<!-- 证书模板管理 -->
<script setup lang="ts">
import { Page } from '@vben/common-ui';
import { onMounted, reactive, toRefs, ref, computed } from 'vue';
import { ElMessageBox, ElMessage } from "element-plus"
import dayjs from 'dayjs';
import { getCertificateTempApi, deleteCertificateTempApi, updateCertificateTempApi } from "#/api/certificate/template"
import { certificateType, certificateStatus, statusColors } from './modules/const'
import { $t } from "#/locales";

import { Query, EditTemplateDialog, PreTemplateDialog, MockTemplateDialog } from './modules/template'
import { trimStringParams } from '#/utils/trimStringParams'
import { Eye, Pencil, Trash2, Ratio } from '@vben/icons';

const editTemplateDialogRef = ref<InstanceType<typeof EditTemplateDialog> | null>(null)
const preTemplateDialogRef = ref<InstanceType<typeof PreTemplateDialog> | null>(null)
const mockTemplateDialogRef = ref<InstanceType<typeof MockTemplateDialog> | null>(null)
const defaultQueryData = {
  name: '',
  type: null,
  // status: null,
  createTime: null
}

const queryData = reactive({ ...defaultQueryData });
const tableLoading = ref(false)
const tableData = ref<any>([])
const total = ref(0)
const pageData = reactive({
  curPage: 1,
  pageSize: 10
})


const getCertificateType = computed(() => {
  return (type: any) => {
    return certificateType.find((_: { type: any }) => _.type === type)?.name || '--'
  }
})

const getCertificateStatus = computed(() => {
  return (status: any) => {
    return certificateStatus.find((_: { status: any }) => _.status === status)?.name || '--'
  }
})

const getTabelData = () => {
  const { curPage, pageSize } = toRefs(pageData)
  const params = {
    curPage: curPage.value,
    pageSize: pageSize.value
  } as any
  const trimData = trimStringParams(queryData)
  console.log(trimData)
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal) {
      if (key === 'createTime' && Array.isArray(kVal)) {
        params['startTime'] = kVal[0]
        params['endTime'] = kVal[1]
      } else {
        params[key] = kVal
      }
    }
  })
  tableLoading.value = true
  getCertificateTempApi(params).then(res => {
    let { data, pageInfo } = res;
    tableData.value = data
    total.value = pageInfo.totalRows
  }).finally(() => {
    tableLoading.value = false
  })
}

const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  getTabelData()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  getTabelData()
}

onMounted(() => {
  getTabelData()
})

const editCert = (data: any) => {
  editTemplateDialogRef.value?.inint(data)
}

const deleteCert = (data: any) => {
  console.log(data)
  ElMessageBox.confirm(
    `${$t('common.confirmTxt', [$t('common.deleteTxt', [$t('certificateTemplate.certificateTemplateTxt')])])}`,
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      deleteCertificateTempApi(data.id).then(() => {
        ElMessage.success($t('common.deleteTxt', [$t('common.successTxt')]))
        getTabelData()
      }).finally(() => {
      })
    })
    .catch(() => { })
}

const resetQuery = () => {
  Object.assign(queryData, defaultQueryData)
  getTabelData()
}

const preTemplateImage = (data: any) => {
  if (!!data.templateFile) {
    preTemplateDialogRef.value?.inint(data)
  } else {
    ElMessage.warning($t('certificateTemplate.noTemplateFileTxt'))
  }
}

const setCertTemplate = (data: any) => {
  mockTemplateDialogRef.value?.inint(data)
}

</script>
<template>
  <Page class="h-full">
    <div class="flex flex-col h-full bg-[#fff] p-[24px] rounded-sm">
      <Query v-model="queryData" class="mb-[5px]" @query-data="getTabelData" @reset-query="resetQuery" />
      <el-table :data="tableData" class="flex-1 overflow-auto" v-loading="tableLoading">
        <el-table-column align="center" width="60px" type="index" :label="$t('common.numberIdxTxt')" />
        <el-table-column prop="name" min-width="210" :label="$t('certificateTemplate.certificateNameTxt')" />
        <el-table-column prop="type" min-width="200" :label="$t('certificateTemplate.certificateTypeTxt')">
          <template #default="{ row }">
            <div>{{ getCertificateType(row.type) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" min-width="200" :label="$t('certificateTemplate.certificateStatusTxt')">
          <template #default="{ row }">
            <div>
              <span class="mr-[5px] inline-block w-[10px] h-[10px] rounded-[5px]" :style="{ backgroundColor: statusColors[`status${row.status}` as keyof typeof statusColors] }"></span>
              <span>{{ getCertificateStatus(row.status) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('common.createTimeTxt')" min-width="200">
          <template #default="{ row }">
            <div>{{ row?.firstCreateTime ? dayjs(row?.firstCreateTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column min-width="150" :label="$t('common.operationTxt')">
          <template #default="{ row }">
            <el-tooltip effect="dark" :content="$t('common.setCertTemplateTxt')" :show-after="1000" placement="top">
              <el-badge :offset="[0, 5]" class="mr-[12px]" :is-dot="!!row.draft">
                <el-button link @click="setCertTemplate(row)" :icon="Ratio"></el-button>
              </el-badge>
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('certificateTemplate.previewCertTemplateTxt')" :show-after="1000" placement="top">
              <el-button link @click="preTemplateImage(row)" :icon="Eye"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('common.editTxt')" :show-after="1000" placement="top">
              <el-button :icon="Pencil" :disabled="row.status === 3" link @click="editCert(row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
              <el-button :icon="Trash2" :disabled="row.status === 2" link @click="deleteCert(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :total="total"></el-pagination>
      <EditTemplateDialog ref="editTemplateDialogRef" @query-table="getTabelData"></EditTemplateDialog>
      <PreTemplateDialog ref="preTemplateDialogRef"></PreTemplateDialog>
      <MockTemplateDialog ref="mockTemplateDialogRef" @query-table="getTabelData"></MockTemplateDialog>
    </div>
  </Page>
</template>
